<?php

namespace App\Repository;

use App\Models\SpecialApply;

class SpecialApplyRepo extends BaseRepo
{
    /**
     * 根据商户号查询创作者全部藏品
     * @param string $access_mid
     * @param int $page
     * @param int $page_size
     * @return array
     * Author:xsc
     * Time:2023/8/31 20:25
     */
    public function getListByAccessMid(string $access_mid, int $page = 1, int $page_size = 20)
    {
        $fields = [
            's.id as special_id', 's.title', 's.thumb', 's.all_count', 's.create_time',
            's.apply_status', 's.reason', 's.cast_status', 's.status', 's.ca_cast_count as cast_count',
        ];
        return SpecialApply::query()
            ->from('special', 's')
            ->join('merchants_info as i', 'i.mer_id', '=', 's.merchants_id')
            ->where('s.type', 9)
            ->where('i.access_mid', $access_mid)
            ->orderBy('s.id', 'asc')
            ->forPage($page, $page_size)
            ->get($fields)
            ->toArray();
    }

    /**
     * 根据商户号查询创作者全部藏品数量
     * @param $access_mid
     * @return int
     * Author:xsc
     * Time:2023/9/7 13:41
     */
    public function getCountByAccessMid($access_mid): int
    {
        return SpecialApply::query()
            ->from('special', 's')
            ->join('merchants_info as i', 'i.mer_id', '=', 's.merchants_id')
            ->where('s.type', 9)
            ->where('i.access_mid', $access_mid)
            ->count();
    }

    /**
     * 根据商户号和藏品id查询藏品详情
     * @param string $access_mid
     * @param int $special_id
     * @return array
     * Author:xsc
     * Time:2023/9/1 10:06
     */
    public function detail(string $access_mid, int $special_id)
    {
        $fields = [
            's.id as special_id', 's.title', 's.thumb', 's.base_price', 's.all_count', 's.create_time',
            's.apply_status', 's.reason', 's.cast_status', 's.status', 's.ca_cast_count as cast_count',
        ];
        $res = SpecialApply::query()
            ->from('special', 's')
            ->join('merchants_info as i', 'i.mer_id', '=', 's.merchants_id')
            ->where('s.id', $special_id)
            //->where('s.type', 9)
            ->where('i.access_mid', $access_mid)
            ->first($fields);
        return $res ? $res->toArray() : [];
    }

    public function getById($id)
    {
        return SpecialApply::query()->find($id);
    }

    public function getByCode($code)
    {
        return SpecialApply::query()->where("code",$code)->first();
    }

    /**
     * 新增/更新藏品
     * @param array $data
     * @param int $id
     * @return int
     * Author:xsc
     * Time:2023/9/1 16:01
     */
    public function save(array $data, int $id = 0)
    {
        if ($id) {
            return SpecialApply::query()->where('id', $id)->update($data);
        } else {
            return SpecialApply::query()->insertGetId($data);
        }
    }

}
